import json
import math
import uuid
from io import StringIO

import requests
from celery.utils.serialization import jsonify
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect,HttpResponse
from django.shortcuts import render
from matplotlib import pyplot as plt
from rest_framework.viewsets import ModelViewSet
from Home.models import *
# NavigationModel,CourseModel,ChannelGoodsMdoel,ChannelModel
from Home.ser.NavigationSer import *
# NavigationSerilize,CategorySerilize,ChannelCategorySer,SonSerialize,CourseSerilize,ChannelGoodsSer

from rest_framework.views import APIView
from Home.models import CategoryModel
from rest_framework.response import Response

from django.db.models import Q
# Create your views here.

class NavigationModelViewset(ModelViewSet):
    queryset = NavigationModel.objects.all()
    serializer_class = NavigationSerilize
    lookup_field = 'pk'
    lookup_url_kwarg = "id"

def getUserid(request):
    info = g.jwt_decode(request.headers.get("token"))
    print(info)
    return info.get("userid")


class CategoryApiView(APIView):
    def get(self,request):
        viewdata=CategoryModel.objects.filter(pid__isnull=True,is_delete=False).all()
        viewobj=CategorySerilize(viewdata,many=True)
        data=viewobj.data
        print(data)
        lista=[]
        for i in data:
            sondata1 = i["son"]
            print(sondata1)
            sondata=sondata1[0:2]
            son=SonSerialize(sondata,many=True)
            lista.append({"id":i["id"],"name":i["name"],"son":son.data})
        return Response({"message":"访问成功","data":lista})


class CoueseApiView(APIView):
    def get(self,requset,id):
        categorylist=CategoryModel.objects.filter(is_delete=False,id=id)
        categoryobj=CategorySerilize(categorylist, many=True)
        catedata = categoryobj.data

        courseList=CourseModel.objects.filter(topid__exact=id,is_recommend__exact=False)
        courseobj=CourseSerilize(courseList,many=True)
        coursedata=courseobj.data
        dict={

            "catedata":catedata,
            "coursedata":coursedata
        }


        return Response({"message":"访问成功","data":dict})


class HomeCourse(APIView):
    # def get(self,request):
    #     channel = ChannelModel.objects.order_by('sort').all()
    #     clist = []
    #     for i in channel:
    #         cateslist =[]
    #         cates = i.cates.order_by('sort').all()
    #         for j in cates:
    #             courses = j.courses.all()
    #             ser = ChannelGoodsSer(courses,many=True)
    #             cateslist.append({"id":j.id,'name':j.name,'courses':ser.data})
    #         cdict = {"id":i.id,'name':i.name,'picurl':i.picurl,'cates':cateslist}
    #         clist.append(cdict)
    #     return Response({"code":200,'clist':clist})

    # def get(self, request):
    #     # 接收参数
    #     # 获取所有频道
    #     channel = ChannelModel.objects.order_by('sort').all()
    #     clist = []
    #
    #     # 遍历频道，获取频道下的分类
    #     for i in channel:
    #         cates = i.cates.order_by('sort').all()
    #         ser = ChannelCategorySer(cates, many=True)
    #         coursel = []
    #         # 分类是否为空
    #         if ser.data:
    #             # 取第一个分类的id
    #             cid = ser.data[0]['id']
    #             # 获取第一个分类下的课程
    #             courses = ChannelGoodsMdoel.objects.filter(ccates_id=cid).all()
    #             cser = ChannelGoodsSer(courses, many=True)
    #             coursel = cser.data
    #
    #         cdict = {"id": i.id, 'name': i.name, 'picurl': i.picurl, 'cates': ser.data, 'courses': coursel}
    #         clist.append(cdict)
    #
    #     cid = int(request.GET.get('catesid'))
    #     ind = int(request.GET.get('ind'))
    #     # 是否点击
    #     if cid:
    #         # 根据点击获取课程
    #         courses = ChannelGoodsMdoel.objects.filter(ccates_id=cid).all()
    #         cser = ChannelGoodsSer(courses, many=True)
    #         coursel = cser.data
    #         # 更新楼层
    #         clist[ind]['courses'] = coursel
    #
    #     return Response({"code": 200, 'clist': clist})

    def get(self,request):
        # 接收参数
        # 获取所有频道
        channel = ChannelModel.objects.order_by('sort').all()
        clist = []
        # 遍历频道，获取频道下的分类
        for i in channel:
            cates = i.cates.order_by('sort').all()
            ser = ChannelCategorySer(cates, many=True)
            coursel = []
            # 分类是否为空
            if ser.data:
                # 取第一个分类的id
                cid = ser.data[0]['id']
                # 获取第一个分类下的课程
                courses = ChannelGoodsMdoel.objects.filter(ccates_id=cid).all()
                cser = ChannelGoodsSer(courses, many=True)
                coursel = cser.data

            cdict = {"id": i.id, 'name': i.name, 'picurl': i.picurl, 'courses':coursel ,'cates': ser.data}

            clist.append(cdict)
        cid = int(request.GET.get('catesid'))
        ind = int(request.GET.get('ind'))
        # 是否点击
        if cid:
            # 根据点击获取课程
            courses = ChannelGoodsMdoel.objects.filter(ccates_id=cid).all()
            cser = ChannelGoodsSer(courses, many=True)
            coursel = cser.data
            # 更新楼层
            clist[ind]['courses'] = coursel

        return Response({"code": 200, 'clist': clist})

class CourseTitle(APIView):
    def get(self,request):

        topid=request.GET.get("topid")
        print(topid,"topid")
        cateid=request.GET.get("cateid")
        print(cateid,"cateid")
        sorted=request.GET.get("sorted") if(request.GET.get("sorted")) else "id"
        page=int(request.GET.get("page")) if(request.GET.get("page")) else 1
        print(page)
        pageSize=int(request.GET.get("page_size")) if(request.GET.get("page_size")) else 2
        datacate=CategoryModel.objects.filter(pid__isnull=True).all()
        sercate=SonSerialize(datacate,many=True)
        datacateer=[]
        if topid:
            datacateer=CategoryModel.objects.filter(pid__exact=topid)
        else:
            datacateer = CategoryModel.objects.filter(pid__isnull=False)

        sercateer = SonSerialize(datacateer, many=True)
        print(sorted)

        query = Q()
        if cateid:
            # 如果有搜索条件，构建查询
            query = Q(pid__exact=cateid)
        query1 = Q()
        if topid:
            # 如果有搜索条件，构建查询
            query1 = Q(topid__exact=topid)
        datacourse=CourseModel.objects.filter(query).filter(query1).order_by(sorted)
        paginator = Paginator(datacourse, pageSize)

        datacourse=paginator.get_page(page)
        sercourse = CourseSerilize(datacourse, many=True)

        #自己写入上一页和下一页的页码
        total=math.ceil(paginator.count/pageSize)
        if(page==1):
            pre=None
            if(total==1):
                netxtPage=None
            else:
                netxtPage=page+1
        elif page==math.ceil(paginator.count/int(pageSize)):
            pre=page-1
            netxtPage=None
        else:
            pre=page-1
            netxtPage=page+1


        clist={'datacate':sercate.data,"sercateer":sercateer.data,"sercourse":sercourse.data,"page":page,"pige_size":pageSize,"total":paginator.count,
               "previous":pre,"next":netxtPage}

        return Response({"code": 200, 'clist': clist})


from Home.tools.Myredis import r
class TestRedis(APIView):
    def get(self,request):
        r.set_srt("kk","kk")
        r.get_str("kk")
        print(r.get_str("kk"))
        return Response({"code": 200, 'clist': r.get_str("kk")})



class CourseDetail(APIView):
    def get(self,request,id):
        # try:
        c1=CourseModel.objects.get(id=id)
        c1=CourseSerilize(c1)

        chapterList=ChapterModel.objects.filter(course_id=id).order_by("display_order")
        chapterIdList=[]
        for i in chapterList:
            chapterIdList.append(i.id)
        chapterser= ChapterSer(chapterList,many=True)

        lessonList=LessonModel.objects.filter(chapter__in=chapterIdList).order_by("chapter_id","display_order")
        lessonList=LessonSer(lessonList,many=True)

        commentList=CommentModel.objects.filter(courseid__exact=id)
        commentIdList = []
        for i in commentList:
            commentIdList.append(i.id)

        commentList=CommentSer(commentList,many=True)

        replyList=ReplyModel.objects.filter(commentid__in=commentIdList)
        replyList=ReplySer(replyList,many=True)

        TeacherModel.objects.get()

        dict={
            "detail":c1.data,
            "chapterList":chapterser.data,
            "lessonList":lessonList.data,
            "commentList":commentList.data,
            "replyList":replyList.data,


        }
        return Response({"code": 1000, 'detail': dict})
        # except:
        #     return Response({"code": 1001, 'clist': "此详情不存在"})


from Home.tools.SendMessage import   send_message
from Home.tools.Myredis import r
from Home.tools.AuthQuery import g
import re
import  random
import time


class MessageView(APIView):
    #返回验证码，redis中限制时间

    def post(self,request):
        print(request.data)
        phone = str(request.data.get("phone"))
        print(phone)
        ret_phone=re.match(r"^1[3-9]\d{9}$",phone)
        print(ret_phone)
        code=str(random.randint(1000,9999))
        if (ret_phone):
            # 调用发送手机号的方法

            # 从redis中获取数据
            if r.get_str(phone):
                return Response({"message": "验证码已发送，请等待","code":1000})
            else:
                try:
                    send_message(phone, code)
                except:
                    return Response({"msgcode": "发送失败", "code": 1001})
                codeMsg =True
                if(codeMsg):

                    r.setex_str(phone,code,1000)
                    return Response({"msgcode": codeMsg,"code":1000})
                else:
                    return Response({"message": "验证码发送失败", "code": 1001})
        else:
            return Response({"message": "验证码输入不正确","code":1001})


class LoginView(APIView):
    #前台调用上个接口成功之后进行登录接口
    def post(self,request):
        #先从用户表中查询是否由此用户，有的话进行登录，
        #用手机登录的话，只存储手机信息，然后所有的信息都是默认生成的
        phone=str(request.data.get("phone"))
        print(phone)
        codeMsgg=str(request.data.get("codeMsg"))
        code=r.getex_str(phone)
        print(code)
        print(codeMsgg)
        if(codeMsgg==code):
            try:
                c1 = CusersModel.objects.get(phone__exact=phone)
                # 没有进行注册
            except:
                c1 = CusersModel()
                c1.name="moren"
                c1.phone=phone
                c1.save()

            # 二者都要进行生成token,
            info={
                "id":c1.id,
                "name":c1.name,
                "phone":c1.phone,
                "exp":int(time.time())+3600

            }
            # g.jwt_encode(info)
            token =g.jwt_encode(info)
            print(token)
            # 将其放入到redis中
            r.setex_str(str(phone) + "token", token, 10000)

            # 返回结果中带入token
            response = Response({"message": "登录成功","token":token})

            return response
        else:
            return Response({"message": "登录失败"})


#钉钉调用函数
from Home.factory.LoginFactory import dd
class ToDingDingView(APIView):
    def get(self, request):
        # from urllib.parse import quote
        # params = [
        #     f"redirect_uri={quote('http://127.0.0.1:8000/home/nav/dingdingCallBack/')}",
        #     "response_type=code",
        #     "client_id=ding5vqytdbueu3cicyt",
        #     "scope=openid",
        #     "prompt=consent"
        # ]
        # url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        url=dd.create_login()
        return Response({"url": url})

#钉钉回调函数
from urllib.parse import urlencode

class DingDingCallBack(APIView):
    def get(self, request):
        # authCode = request.query_params.get('authCode')

        # # 根据authCode获取用户accessToken
        # data = {
        #     "clientId": "ding5vqytdbueu3cicyt",
        #     "clientSecret": "M8h_VRftMfxCv3Vi60FSpZQBY8s8IUI1QQBoHYc8N_D3lDWUXXn2BtGSWnuRRX04",
        #     "code": authCode,
        #     "grantType": "authorization_code"
        # }
        # resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        # accessToken = resp.get('accessToken')
        #
        # # 根据accessToken获取用户信息
        # headers = {"x-acs-dingtalk-access-token": accessToken}
        # resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
        # name = resp.get('nick')
        # uid = resp.get('openId')
        # phone = resp.get('mobile')
        #
        #
        #
        # # 登录，写入三方登录表和用户表
        # sfl = SFModel.objects.filter(uid=uid, types=1).first()
        # print(sfl)
        #
        #
        # if not sfl:
        #     # 写入用户表
        #     # 手机号用户存在直接绑定,不存在注册新用户
        #     user = CusersModel.objects.filter(phone=phone).first()
        #     if not user:
        #         userinfo = {
        #             "name": name,
        #             "phone": phone,
        #             # "password": phone,
        #             # "username": phone
        #         }
        #         us = CuserSer(data=userinfo)
        #         if us.is_valid():
        #             print("sabve")
        #             user = us.save()
        #         else:
        #             return Response({"code": 10001, "msg": (us.errors)})
        #     # 写入三方登录表
        #     sfinfo = {
        #         "types": 1,
        #         "token": accessToken,
        #         "uid": uid,
        #         "users": user.id
        #     }
        #     sfs = SFser(data=sfinfo)
        #     print(sfs.is_valid())
        #     if sfs.is_valid():
        #         sfs.save()
        #     else:
        #         return Response({"code": 10001, "msg": (sfs.errors)})
        # else:
        #     print(sfl)
        #     user = sfl.users
        #
        #     sfl.token = accessToken
        #     sfl.save()
        # print("111111")
        # # 生成jwt token并返回前端
        # payload = {"userid": user.id, "username": user.name, "exp": int(time.time()) + 60 * 60 * 2}
        # token = g.jwt_encode(payload)
        # payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
        # refreshToken = g.jwt_encode(payload)
        # query = [f"userid={payload['userid']}", f"username={payload['username']}", f"token={token}",
        #          f"refreshToken={refreshToken}"]
        # # return HttpResponseRedirect(f'http://localhost:3000/ddtoken/?{"&".join(query)}')
        # query_params = urlencode({
        #     'userid': str(user.id),
        #     'token': token
        # })
        # redirect_url = f'http://localhost:3000/ddtoken/?{query_params}'
        redirect_url=dd.rollback(request)


        return HttpResponseRedirect(redirect_url)


class ShopCarView(APIView):
    def get(self,request):

        info=g.jwt_decode(request.headers.get("token"))
        print(info)
        slist=ShopCarModel.objects.filter(useridd__exact=info.get("userid"))
        shopser=ShopCarSer(slist,many=True)
        return Response({"message": "查询成功", "slist": shopser.data})
    def post(self,request):
        courseidd=request.data.get("courseidd")
        useridd=request.data.get("useridd")
        shoplist=ShopCarModel.objects.filter(useridd__exact=useridd,courseidd__exact=courseidd)
        if(len(shoplist)==0):
            shopser = ShopCarSer(data=request.data)

            if (shopser.is_valid()):
                shopser.save()
                return Response({"message": "添加成功", "code": 200})
            else:

                # return Response({"message": "添加失败", "code": 200})

                return Response(shopser.errors)
        else:
            return Response({"message": "添加失败，已经存在", "code": 200})

    def patch(self,request):
        courseidd=request.data.get("course_id")
        selected=request.data.get("selected")
        shop=ShopCarModel.objects.get(id=courseidd)
        shop.is_select=selected
        shop.save()
        return Response({"message": "修改成功", "code": 200})

    def delete(self,request):

        courseidd=request.data.get("course_id")

        s1=ShopCarModel.objects.filter(id=courseidd)
        print(s1)
        k1=s1.delete()
        print(k1)
        return Response({"message": "删除成功", "code": 200})

    def put(self,request):

        selected = request.data.get("selected")
        info = g.jwt_decode(request.headers.get("token"))
        print(info)
        count = ShopCarModel.objects.filter(useridd__exact=info.get("userid")).update(is_select=selected)
        if(count!=0):
            return Response({"message": "修改成功", "code": 200})
        else:
            return Response({"message": "修改失败", "code": 200})

class UserCouponView(APIView):
    def get(self,request):
        #通过用户id查询表中的优惠券是否可以使用，
        userid=getUserid(request)
        #时间过滤每家
        usercouponlist=UserCouponModel.objects.filter(user_id=userid,userStatus=1)
        usercouponser=UserCouponSer(usercouponlist,many=True)
        user=CusersModel.objects.get(id=userid)
        # u1=CuserSer(user)

        slist = ShopCarModel.objects.filter(useridd__exact=userid,is_select__exact=True)
        shopser = ShopCarSer(slist, many=True)


        # "message": "优惠券范文成功", ""usercouponlist"": usercouponser.data}
        return Response({"message": "访问成功", "usercouponlist": usercouponser.data,"score":user.score,"slist":shopser.data})


#为了保证接口的幂等性
class PaySecirty(APIView):
    def get(self,request):
        #获取用户id，和网页传入的固定di
        print(request.GET,"fffffffffffffffffffffffff")
        payid=request.GET.get("payid")
        userid = getUserid(request)
        #将他们作为key值存入redis中
        r.set_srt(str(payid)+str(userid),"1次")
        return Response({"payid":str(payid)+str(userid)})
import datetime
from django.db  import transaction

class OrdersView(APIView):
    def get(self,request):
        userid = getUserid(request)
        orderList=OrdersModel.objects.filter(userid__exact=userid)

        # listdict=[]
        # for i in orderList:
        #     dict={
        #         "orderno":i.orderno,
        #         # "order_courses":json.dumps(i.ordersdetailmodel_set)
        #     }
        #
        #     listdict.append(dict)
        # print(orderList)

        list=OrdersSer(instance=orderList,many=True)

        listdict=list.data
        # if(list.is_valid()):
        return Response({"message": "查询成功", "orderlist": listdict})
        # else:
        #     print(list.errors)
        #     return Response({"message": list.errors})

    def post(self,request):
        #获取用户信息和选中的商品
        userid = getUserid(request)
        print(userid,"------------")
        payid=request.data.get("payid")
        user_coupon_id=request.data.get("user_coupon_id")
        credit=request.data.get("credit")
        #判断是否是第一次进行支付 ,是的话，就进行删除
        payid=r.get_str(payid)
        print(payid,"kkkk")
        if(payid):
            r.del_str("payid")
            # save_id = transaction.savepoint()
            #生成订单号 datetime.datetime.now().strftime("%Y%m%d%h%m%s")
            # orderno = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+str(userid) + str(random.randint(10000, 99999))
            orderno=uuid.uuid1().hex
            orderinfo = {
                "orderno": orderno,
                "userid": userid,
                'userid_id':userid,
                "status": 1,
                "orders_status": 1,
                "pay_type": 1,

                "tmoney":0,
                "transaction":uuid.uuid1().hex

            }
            print(orderinfo)
            orderser = OrdersSer(data=orderinfo)

            if( orderser.is_valid()):
                orderser.save()

            order=OrdersModel.objects.get(orderno=orderno)
            #计算总价钱
            totalMoney=0
            #从购物车列表进行商品的

            shoplist=ShopCarModel.objects.filter(useridd__exact=userid,is_select__exact=True)
            shopDetaillist=[]
            for i in shoplist:
                # dict={
                #     "user":i.useridd,
                #     "orders" : order,
                #     "course":i.courseidd,
                #     "name" :"不知道",
                #     "price" : i.courseidd.price,
                #
                # }

                o1=OrdersDetailModel()
                o1.user=i.useridd
                o1.orders=order
                o1.course=i.courseidd
                o1.name="不知道"
                o1.price=i.courseidd.price
                totalMoney+=i.courseidd.price
                o1.save()
                # totalMoney+=o1.price
                # shopDetaillist.append(dict)


            # details=OrderDetailSer(data=list,many=True)
            #是否使用优惠券
            if(user_coupon_id):
                usercou=UserCouponModel.objects.filter(id=user_coupon_id).first()
                #获取券的优惠价格
                out=UserCouponSer(instance=usercou).data.get("couponn").get("out")
                print(out,"0000000")
                #保存用户的使用券
                usercou.userStatus=2
                usercou.save()
                order.couponid=user_coupon_id
                order.couponmoney=out
                order.tmoney = totalMoney
                order.pay_money=totalMoney- out



            #是否使用积分
            if(credit):
                u1=CusersModel.objects.filter(id=userid).first()
                if(credit >u1.score):
                    u1.score=0
                    order.tmoney = totalMoney
                    order.pay_money = totalMoney - u1.score
                    order.score = u1.score
                else:
                    u1.score -= credit
                    order.tmoney = totalMoney
                    order.pay_money = totalMoney - credit
                    order.score=credit

            order.save()
            r.zset_zadd('orderscancel1', int(time.time())+60, orderno)
            # orderinfo["tmoney"]=totalMoney
            # for i in shopDetaillist:
            #
            #     oo = OrderDetailSer(data=i)
            #     if (oo.is_valid()):
            #         oo.save()
            #
            #     else:
            #         print(oo.errors)
            #         return Response({"message": "数据不成功"})
            shoplist.delete()
            return Response({"message": "通过了","id":orderno})

        else:
            return Response({"message":"已经进行过一次支付了，请等待"})



from Home.tools.SendMessage import get_alipay
class KeyView(APIView):

    def get(self, request):
        # 获取参数
        data = request.GET
        rdata = {k: v for k, v in data.items()}
        # 验证签名
        sign = rdata.pop('sign')

        pay = get_alipay()
        flag = pay.verify(rdata, sign)
        # 业务逻辑
        if flag:
            # 更新订单表
            orderno = data['out_trade_no']
            transaction_no = data['trade_no']
            order=OrdersModel.objects.filter(orderno__exact=orderno).first()
            order.transaction=transaction_no
            order.pay_type=1
            order.orders_status=2
            order.status=2
            order.save()
            # 调用支付宝查询接口查询    如果不知道结果，可以使用这个进行查询，


            #给用户添加课程和章节信息
            orderlist=order.detailorder.all()
            for i in orderlist:
                uc=UserCourseModel()
                uc.userid=order.userid
                uc.courseid=OrdersDetailModel.objects.get(id=i.id).course
                uc.progress=0
                uc.save()



            # 在队列中删除当前订单号
            r.zset_zrem('orderscancel1', orderno)
            # 写入用户课程表

            return HttpResponseRedirect("http://localhost:3000/alipay/?orderno="+orderno)

        return HttpResponseRedirect("http://localhost:3000/error")
    def post(self,request):
        #通过订单号搜索价钱


        orderno=request.data.get("order_id")
        price=OrdersModel.objects.filter(orderno__exact=orderno).first().pay_money
        print(price)
        pay=get_alipay()
        query_params=pay.direct_pay(
            subject="订单支付",
            out_trade_no=str(orderno),
            total_amount=float(price),
        )
        payUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(query_params)
        return Response({"code":200,'url':payUrl})

class OrderGet(APIView):
    def get(self,request):
        orderno=request.GET.get("orderno")
        order=OrdersModel.objects.filter(orderno__exact=orderno).first()
        orderdata=OrdersSer(instance=order)
        return Response({"message":"访问chengg","list":orderdata.data})

    def patch(self,request):
        order_id=request.data.get("order_id")
        order=OrdersModel.objects.filter(orderno__exact=order_id).first()
        order.orders_status=3
        odlist=order.detailorder.all()
        # cannallist=[]
        for i in odlist:
            u1=UserCourserCannal()
            u1.course=i.course
            u1.user=order.userid
            u1.save()
            # cannallist.append(u1)
        order.save()
        # uu=UserCourserCannalSer(cannallist,many=True)
        return Response({"message": "访问成功"})
        # if(uu.is_valid()):
        #     uu.save()
        #     return Response({"message": "访问成功"})
        # else:
        #     return Response({"message": uu.errors})

class OrderDelGet(APIView):
    def delete(self,request,order_id):

        order = OrdersModel.objects.filter(orderno__exact=order_id)
        print(order)
        print(order.delete())
        return Response({"message": "删除成功"})


from base.tasks import cancelorders
def test(request):
    cancelorders()
    return HttpResponse("成功")


class UserCourseView(APIView):
    def get(self,request):
        page=int(request.query_params.get("page",1))
        size=int(request.query_params.get("size",1))
        uc=UserCourseModel.objects.all()
        pagee=Paginator(uc,size)
        pagee.page(page)
        try:
            page_obj = pagee.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，则返回第一页
            page_obj = pagee.page(1)
        except EmptyPage:
            # 如果页码超出范围，则返回最后一页
            page_obj = pagee.page(pagee.num_pages)

        list=page_obj.object_list
        ucdata=UserCourseSer(instance=list,many=True)


        return Response({"data": ucdata.data,"pre":page_obj.has_previous(),"next":page_obj.has_next(),"count":page_obj.number})

class CommentView(APIView):
    def post(self,request):
        content=request.data.get("content")
        userid=request.data.get("userid")
        courseid=request.data.get("courseid")
        print(content)
        print(userid)
        print(courseid)
        coment=CommentModel()
        coment.courseid=CourseModel.objects.get(id=courseid)
        coment.userid=CusersModel.objects.get(id=userid)
        coment.message=content
        coment.score=0
        coment.save()
        return Response({"message": "评论成功"})

from elasticsearch import Elasticsearch
class QuerySome(APIView):
    def get(self,request):
        name=request.query_params.get("text")
        print(name,"1111111")
        page=int(request.query_params.get("page",1))
        print(page)
        pagesize=int(request.query_params.get("size",1))
        print(pagesize)
        es = Elasticsearch("http://101.42.31.212:9200/")
        dsl = {
            "query": {
                "bool": {
                    "must": [
                        {"match": {"name": name}},

                    ]
                }
            },
            "from": (page-1)*pagesize,
            "size": pagesize,

        }
        results=[]
        res = es.search(index="coursees", body=dsl)
        # print(res)
        for hit in res['hits']['hits']:
            # print("111111111")
            results.append(hit['_source'])
        previous=False
        next=False
        if( page*pagesize < int(res['hits']["total"].get("value")) ):
            next=True
            if(page != 1):
                print(page != 1)
                previous=True
        else:

            if (page != 1):

                previous = True
            next = False
        return Response({"res": results,"total":res['hits']["total"].get("value"),"previous":previous,"next":next})

class TestPhoneView(APIView):
    def post(self,request):
        print(request.data)
        t1=TestModel()
        t1.testno=request.data.get("testno")
        print(t1.testno)
        t1.inputcontent=request.data.get("inputcontent")
        dictionary = json.loads(t1.inputcontent)
        print(dictionary)
        t1.inputurl=request.data.get("inputurl")
        t1.inputmethod=request.data.get("inputmethod")
        t1.result_yuce=request.data.get("result_yuce")
        t1.level=request.data.get("level")
        t1.result_end=""

        t1.save()
        return Response({"message":"保存成功"})
    def get(self,request):
        m1=MessageView()
        testlist=TestModel.objects.all()
        for i in testlist:
            print(i.inputmethod=="post")
            # response = requests.get('http://example.com')
            # response = requests.post('http://example.com', data={'key': 'value'})
            if(i.inputmethod=="post"):
                print("33333333")
                response = requests.post(i.inputurl,json= json.loads(i.inputcontent))

                dataa=json.loads(response.content.decode())

                i.result_end = dataa.get("code")
                if i.result_yuce == str( dataa.get("code")):

                    i.success = True
                else:
                    i.success = False
                print(i.success, "succ")
                i.save()




        testlist=TestModel.objects.all()
        testlist=TestPhoneSer(instance=testlist,many=True)
        return Response({"message": "保存成功","data":testlist.data})

import os
from fuguangserver import settings
import pandas as pd
import chardet

from sqlalchemy import create_engine
from Home.views_Matplotlib import getMonth
from django.http import HttpResponse
import csv
# from .models import YourModel  # 替换YourModel为你的模型名称

class InportEView(APIView):
    def post(self,request):
        # "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"


        file = request.FILES['file']

        # 生成文件路径
        file_path = os.path.join(settings.MEDIA_ROOT, file.name)
        print(file_path)
        with open(file_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        username = 'root'
        password = '123456'
        host = 'localhost'
        database = 'fuguang'
        engine = create_engine(f'mysql+pymysql://{username}:{password}@{host}/{database}')
        df = pd.read_csv(file_path,encoding='utf-8')
        df.to_sql('testphone', con=engine, if_exists='replace', index=False)

        return Response({"message": "保存成功"})

    def get(self,request):
        data=getMonth(request)
        #请求头
        # # 创建一个HttpResponse对象，其内容类型为text/csv
        # response = HttpResponse(content_type='text/csv')
        # # 设置响应头，指定下载的文件名
        # response['Content-Disposition'] = 'attachment; filename="export.csv"'
        #
        # # 创建一个csv.writer对象
        # writer = csv.writer(response)
        #
        # # 写入CSV文件的头部信息
        # writer.writerow(['month', 'count'])  # 替换字段名称为你的模型的实际字段名称

        # 获取所有模型实例

        file_path = os.path.join(settings.MEDIA_ROOT, 'export.csv')

        # 打开文件，准备写入CSV数据
        with open(file_path, mode='w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)

            # 写入CSV文件的头部信息
            writer.writerow(['month', 'count'])


            # 遍历模型实例并将它们写入CSV文件
            for obj in data:
                # 假设Field1, Field2, Field3是模型中的字段
                print(obj)
                writer.writerow([obj[0], obj[1]])

        # starbucks = pd.read_csv("./data/starbucks/directory.csv")
        # count = starbucks.groupby(['Country']).count()
        #
        # count['Brand'].plot(kind='bar', figsize=(20, 8))
        # plt.show()

        starbucks = pd.read_csv(file_path)
        # 按照国家分组，求出每个国家的星巴克零售店数量
        count = starbucks.groupby(['month']).count()
        count['count'].plot(kind='bar', figsize=(20, 8))
        plt.show()

        return Response({"message": "保存成功"})

